import axios from 'axios'
import {Message, MessageBox} from 'element-ui'
import cookie from 'js-cookie'
import appConfig from '@/utils/app-config'
import commonUtil from "./commonUtil";

// 创建axios实例
const service = axios.create({
  // baseURL: 'https://service.zsrey.info', // api的base_url
  baseURL: appConfig.idcUrlConfig.baseURL, // api的base_url
  timeout: 20000 // 请求超时时间
})
// http request 拦截器
service.interceptors.request.use(
  config => {
    if (cookie.get('we_token')) { //we: wisdom education
      config.headers['front-token'] = cookie.get('we_token');
    }
    return config
  },
  err => {
    return Promise.reject(err);
  })
// http response 拦截器
service.interceptors.response.use(
  response => {
    const res = response.data
    // console.log(response)
    // console.log(res)
    if (res.code === '20011') {
      MessageBox('您还未登录, 是否前往登录?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        // 返回 错误代码-1 清除ticket信息并跳转到登录页面
        //debugger

        window.location.href = "/login?r="+commonUtil.getPathName()
      }).catch((response) => {
        if (response === 'cancel') {
          Message.info('已取消')
        }
      })
      //return则不弹出自定义异常消息
      return
    }
    else if (res.code === '20012') {
      cookie.set('we_token', '', -1);
      cookie.set('we_ucenter', '', -1);
      Message({
        message: res.msg || 'error',
        type: 'warning',
        duration: 1000
      })
      setTimeout(function () {
        window.location.href = "/login"
      }, 1000);
      return res.info
    }
    else if(res.code==='80005'){
      return res;
    }
    else if (res.code !== '200') {
      //25000：订单支付中，不做任何提示
      if (res.code !== '25000') {
        Message({
          message: res.msg || 'error',
          type: 'error',
          duration: 5 * 1000
        })
        return Promise.reject('error')
      }

    } else {
      return res.info
    }

  },
  error => {
    console.log('err' + error) // for debug
    Message({
      message: error.message,
      type: 'error',
      duration: 5 * 1000
    })
    return Promise.reject(error)
  }
)
export default service
